package com.xiaolei.library.common;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.xiaolei.library.Base.BaseFragment;
import com.xiaolei.library.Exts.Ext;
import com.xiaolei.library.LifeCycle.ObserverNoneNull;
import com.xiaolei.library.R;
import com.xiaolei.library.Utils.Log;
import com.xiaolei.library.Widgets.XWebView;

/**
 * 承载WebView的fragment
 */
public class WebViewFragment extends BaseFragment
{
    private XWebView web_view;
    private WebViewModel viewModel;
    private final int CHOSE_FILE_REQ_CODE = 0x05;
    private ValueCallback<Uri[]> filePathCallback;

    @Override
    public int getLayoutId()
    {
        return R.layout.lib_fragment_webview;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState)
    {
        viewModel = Ext.create(this, WebViewModel.class);
    }

    @Override
    public void initView()
    {
        web_view = getView().findViewById(R.id.web_view);
        web_view.setWebViewClient(new XWebView.WebViewClient()
        {

        });
        web_view.setWebChromeClient(new XWebView.ChromeClient()
        {
            @Override
            public void onReceivedTitle(WebView view, String title)
            {
                viewModel.title.setValue(title);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result)
            {
                Activity activity = getActivity();
                if (activity != null)
                {
                    Ext.Alert(activity, message);
                }
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result)
            {
                Activity activity = getActivity();
                if (activity != null)
                {
                    Ext.Alert(activity, message);
                }
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage)
            {
                Log.e("Console", consoleMessage.message() + "");
                return super.onConsoleMessage(consoleMessage);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams)
            {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("*/*");
                startActivityForResult(intent, CHOSE_FILE_REQ_CODE);
                WebViewFragment.this.filePathCallback = filePathCallback;
                return true;
            }
        });
    }

    @Override
    public void initEvent()
    {
        // 监听URL变化的事件
        viewModel.url.observe(this, new ObserverNoneNull<String>()
        {
            @Override
            public void changed(@NonNull String url)
            {
                if (web_view != null)
                    web_view.loadUrl(url);
            }
        });
    }

    @Override
    public void loadData()
    {

    }

    @Override
    public void onResume()
    {
        if (web_view != null)
        {
            web_view.onResume();
            web_view.resumeTimers();
        }
        super.onResume();
    }

    @Override
    public void onPause()
    {
        if (web_view != null)
        {
            web_view.onPause();
            web_view.pauseTimers();
        }
        super.onPause();
    }

    @Override
    public void onDestroy()
    {
        if (web_view != null)
        {
            web_view.loadUrl("about:blank");
            web_view.destroy();
        }
        super.onDestroy();
    }

    /**
     * 后退
     *
     * @return 如果可以后退，会自动后退，并且返回true，
     * 如果没有后退，则返回false
     */
    public boolean goBack()
    {
        if (web_view.canGoBack())
        {
            web_view.goBack();
            return true;
        } else
        {
            return false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        if (requestCode == CHOSE_FILE_REQ_CODE)
        {
            if (data == null)
            {
                this.filePathCallback.onReceiveValue(null);
            } else
            {
                Uri uri = data.getData();
                if (uri == null)
                {
                    this.filePathCallback.onReceiveValue(null);
                } else
                {
                    this.filePathCallback.onReceiveValue(new Uri[]{uri});
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 操作WebViewFragment的入口
     */
    public static class WebViewModel extends ViewModel
    {
        public MutableLiveData<String> url = new MutableLiveData<>();
        public MutableLiveData<String> title = new MutableLiveData<>();
    }
}
